package com.example.demo.lc.other;

import java.util.HashMap;
import java.util.Map;

/**
* @author wzh
* @date 2021/8/10 10:42 上午
* @Description    分数到小数
 * https://leetcode-cn.com/problems/fraction-to-recurring-decimal/
*/
public class LeetCode166 {
    public static void main(String[] args) {
        //String result = fractionToDecimal(2, 3);
        //String result = fractionToDecimal(-50, 8);
        String result = fractionToDecimal(-1,-2147483648);
        System.out.println(result);
    }

    /**
    * @author wzh
    * @date 2021/8/10 3:26 下午
    * @Description
     *
    */
    public static String fractionToDecimal(int numerator, int denominator) {
        if(denominator == 0){
            return "0";
        }
        StringBuilder ssb = new StringBuilder();
        if((numerator<0 && denominator>0) || (numerator>0 && denominator<0)){
            ssb.append("-");
        }
        long div = Math.abs(Long.valueOf(numerator));
        long divisor = Math.abs(Long.valueOf(denominator));
        ssb.append(String.valueOf(div / divisor));
        long remaind = div % divisor;
        if(remaind == 0){
            return ssb.toString();
        }
        ssb.append(".");
        Map<Long,Integer> map = new HashMap<>();
        while(remaind != 0){
            if(map.containsKey(remaind)){
                ssb.insert(map.get(remaind),"(");
                ssb.append(")");
                break;
            }
            map.put(remaind,ssb.length());
            remaind *= 10;
            ssb.append(remaind/divisor);
            remaind = remaind%divisor;
        }
        return ssb.toString();
    }
}
